/**
 * 实时波形图数据管理器
 * 负责管理滑动窗口、数据缓存、性能优化等
 */
class RealtimeWaveformManager {
  constructor(options = {}) {
    // 配置参数
    this.windowSize = options.windowSize || 60 // 滑动窗口大小（秒）
    this.maxDataPoints = options.maxDataPoints || 1000 // 最大数据点数
    this.updateInterval = options.updateInterval || 100 // 更新间隔（毫秒）
    this.bufferSize = options.bufferSize || 50 // 缓冲区大小
    
    // 数据存储
    this.dataBuffer = [] // 数据缓冲区
    this.timeData = [] // 时间轴数据
    this.seriesData = new Map() // 系列数据 {seriesName: [data]}
    
    // 性能监控
    this.lastUpdateTime = 0
    this.updateCount = 0
    this.droppedFrames = 0
    
    // 状态管理
    this.isActive = false
    this.updateTimer = null
    
    // 事件监听器
    this.listeners = new Map()
    
    this.init()
  }
  
  /**
   * 初始化管理器
   */
  init() {
    this.startUpdateLoop()
  }
  
  /**
   * 添加数据点到缓冲区
   */
  addDataPoint(dataPoint) {
    if (!this.isActive) return
    
    // 验证数据格式
    if (!this.validateDataPoint(dataPoint)) {
      console.warn('无效的数据点:', dataPoint)
      return
    }
    
    // 添加到缓冲区
    this.dataBuffer.push({
      ...dataPoint,
      timestamp: dataPoint.timestamp || Date.now()
    })
    
    // 限制缓冲区大小
    if (this.dataBuffer.length > this.bufferSize * 2) {
      this.dataBuffer = this.dataBuffer.slice(-this.bufferSize)
    }
  }
  
  /**
   * 验证数据点格式
   */
  validateDataPoint(dataPoint) {
    return dataPoint && 
           typeof dataPoint === 'object' &&
           (dataPoint.timestamp || true) &&
           (typeof dataPoint.xRms === 'number' || 
            typeof dataPoint.yRms === 'number' || 
            typeof dataPoint.zRms === 'number')
  }
  
  /**
   * 处理缓冲区数据
   */
  processBuffer() {
    if (this.dataBuffer.length === 0) return
    
    const currentTime = Date.now()
    const windowMs = this.windowSize * 1000
    const cutoffTime = currentTime - windowMs
    
    // 处理缓冲区中的所有数据
    const processedData = []
    
    while (this.dataBuffer.length > 0) {
      const dataPoint = this.dataBuffer.shift()
      
      // 跳过过期数据
      if (dataPoint.timestamp < cutoffTime) {
        continue
      }
      
      processedData.push(dataPoint)
      
      // 添加到主数据存储
      this.addToMainStorage(dataPoint)
    }
    
    // 清理过期数据
    this.cleanupExpiredData(cutoffTime)
    
    // 限制数据点数量
    this.limitDataPoints()
    
    // 触发更新事件
    if (processedData.length > 0) {
      this.emit('dataUpdated', {
        newData: processedData,
        timeData: this.timeData,
        seriesData: Object.fromEntries(this.seriesData)
      })
    }
  }
  
  /**
   * 添加数据到主存储
   */
  addToMainStorage(dataPoint) {
    const timeStr = new Date(dataPoint.timestamp).toISOString()
    this.timeData.push(timeStr)
    
    // 添加各轴数据
    const axes = ['xRms', 'yRms', 'zRms']
    axes.forEach(axis => {
      if (!this.seriesData.has(axis)) {
        this.seriesData.set(axis, [])
      }
      this.seriesData.get(axis).push(dataPoint[axis] || 0)
    })
  }
  
  /**
   * 清理过期数据
   */
  cleanupExpiredData(cutoffTime) {
    while (this.timeData.length > 0) {
      const firstTime = new Date(this.timeData[0]).getTime()
      if (firstTime < cutoffTime) {
        this.timeData.shift()
        this.seriesData.forEach(series => {
          series.shift()
        })
      } else {
        break
      }
    }
  }
  
  /**
   * 限制数据点数量
   */
  limitDataPoints() {
    if (this.timeData.length > this.maxDataPoints) {
      const removeCount = this.timeData.length - this.maxDataPoints
      this.timeData.splice(0, removeCount)
      this.seriesData.forEach(series => {
        series.splice(0, removeCount)
      })
    }
  }
  
  /**
   * 开始更新循环
   */
  startUpdateLoop() {
    if (this.updateTimer) return
    
    this.updateTimer = setInterval(() => {
      if (this.isActive) {
        const startTime = performance.now()
        this.processBuffer()
        const endTime = performance.now()
        
        // 性能监控
        if (endTime - startTime > this.updateInterval) {
          this.droppedFrames++
        }
        
        this.updateCount++
      }
    }, this.updateInterval)
  }
  
  /**
   * 停止更新循环
   */
  stopUpdateLoop() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
      this.updateTimer = null
    }
  }
  
  /**
   * 启动管理器
   */
  start() {
    this.isActive = true
    this.emit('started')
  }
  
  /**
   * 停止管理器
   */
  stop() {
    this.isActive = false
    this.emit('stopped')
  }
  
  /**
   * 清空所有数据
   */
  clear() {
    this.dataBuffer = []
    this.timeData = []
    this.seriesData.clear()
    this.updateCount = 0
    this.droppedFrames = 0
    this.emit('cleared')
  }
  
  /**
   * 获取性能统计
   */
  getPerformanceStats() {
    return {
      updateCount: this.updateCount,
      droppedFrames: this.droppedFrames,
      bufferSize: this.dataBuffer.length,
      dataPoints: this.timeData.length,
      memoryUsage: this.estimateMemoryUsage()
    }
  }
  
  /**
   * 估算内存使用量
   */
  estimateMemoryUsage() {
    const timeDataSize = this.timeData.length * 24 // 假设每个时间字符串24字节
    const seriesDataSize = Array.from(this.seriesData.values())
      .reduce((total, series) => total + series.length * 8, 0) // 假设每个数字8字节
    const bufferSize = this.dataBuffer.length * 100 // 假设每个数据点100字节
    
    return timeDataSize + seriesDataSize + bufferSize
  }
  
  /**
   * 设置配置
   */
  setConfig(config) {
    if (config.windowSize) this.windowSize = config.windowSize
    if (config.maxDataPoints) this.maxDataPoints = config.maxDataPoints
    if (config.updateInterval) {
      this.updateInterval = config.updateInterval
      this.stopUpdateLoop()
      this.startUpdateLoop()
    }
    if (config.bufferSize) this.bufferSize = config.bufferSize
  }
  
  /**
   * 获取当前数据
   */
  getCurrentData() {
    return {
      timeData: [...this.timeData],
      seriesData: Object.fromEntries(
        Array.from(this.seriesData.entries()).map(([key, value]) => [key, [...value]])
      ),
      stats: this.getPerformanceStats()
    }
  }
  
  /**
   * 添加事件监听器
   */
  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, [])
    }
    this.listeners.get(event).push(callback)
  }
  
  /**
   * 移除事件监听器
   */
  off(event, callback) {
    if (this.listeners.has(event)) {
      const callbacks = this.listeners.get(event)
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    }
  }
  
  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error(`事件处理器执行失败 [${event}]:`, error)
        }
      })
    }
  }
  
  /**
   * 销毁管理器
   */
  destroy() {
    this.stop()
    this.stopUpdateLoop()
    this.clear()
    this.listeners.clear()
  }
}

export default RealtimeWaveformManager
